<template>
  <div class="app-container">
    <div class="filter-container">
      <span v-if="authorityHandle(142)" class="filter-title filter-item">身份所属</span>
      <k-select
       v-if="authorityHandle(142)"
        v-model="listQuery.userType"
        class="filter-item right-item width-control"
        :select-params="dict.type.IDENTITY_TYPE"
        @handleSelectEvent="handleFilter"
      />
      <span class="filter-title filter-item">提取状态</span>
      <k-select
        v-model="listQuery.drawStatus"
        class="filter-item right-item width-control"
        :custom-params="{opations:prizeDrawStatusList, label:'lineName',value:'lineId'}"
        @handleSelectEvent="handleFilter"
      />
      <span class="filter-title filter-item">发起时间</span>
      <k-date-picker v-model="timeValue" class="filter-item right-item" @hqchang="handleFilter" />
      <span class="filter-title filter-item">接受时间</span>
      <k-date-picker v-model="timeValueGet" class="filter-item" @hqchang="handleFilter" />
      <k-input
        v-model.trim="listQuery.key"
        class="filter-item"
        is-search
        placeholder="进行搜索"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      />
    </div>

    <div class="extract_data" v-if="authorityHandle(141)">
      <div class="extract_data_left">
        <p @click="cancelPrizeDraw">取消发货</p>
        <p @click="extendedTakeClick">延长收货</p>
        <!-- <p @click="cancel">取消订单</p> -->
        <!-- <p @click="refund">退款</p> -->
      </div>
      <!-- <span @click="getLimit">提取限制</span> -->
    </div>
    <div v-else style="margin-top: 40px;"></div>

    <!--表格相关 -->
    <el-table
      fit
      :data="listData"
      border
      :show-summary="!authorityHandle(143)"
      :summary-method="getSummaries"
      highlight-current-row
      style="width: 100%; border-radius: 8px; margin-top: 20px;"
      :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <el-table-column min-width="60px" type="selection" align="center" v-if="authorityHandle(141)" />
      <el-table-column prop="userName" min-width="100px" label="用户账号" align="center" show-overflow-tooltip />
      <el-table-column prop="prizeName" min-width="120px" label="礼品名称" align="center" show-overflow-tooltip />
      <el-table-column prop="prizePrice" min-width="100px" label="当时价格" align="center" show-overflow-tooltip />
      <el-table-column prop="nowPrice" min-width="100px" label="此时价格" align="center" show-overflow-tooltip />
      <el-table-column prop="buyPrice" min-width="100px" label="采购价格" sortable="custom" align="center">
        <editable-cell v-model="row.buyPrice" slot-scope="{row}" :show-input="row.editMode" @keyup.enter.native="updateBuyPrice(row)">
          <span slot="content" style="text-align: center;display:block;width:100%;">{{ row.buyPrice }}</span>
        </editable-cell>
      </el-table-column>
      <el-table-column prop="drawsStatusName" min-width="100px" label="提取状态" align="center" show-overflow-tooltip />
      <el-table-column prop="prizeOriginName" min-width="100px" label="礼品来源" align="center" show-overflow-tooltip />
      <el-table-column prop="errorDes" min-width="110px" label="交易报错" align="center" show-overflow-tooltip />
      <el-table-column prop="createTime" min-width="130px" label="发起时间" sortable="custom" align="center" show-overflow-tooltip />
      <el-table-column prop="surplusTime" min-width="130px" label="剩余收货时间" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ getDiffTime(scope.row.surplusTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="recipeTime" min-width="120px" label="接受时间" sortable="custom" align="center" show-overflow-tooltip />
      <el-table-column prop="address" min-width="120px" label="收件人信息" align="center" show-overflow-tooltip />
      <el-table-column prop="courierNumber" min-width="120px" label="快递单号" align="center" show-overflow-tooltip />
      <el-table-column v-if="authorityHandle(141)" min-width="200px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button class="table-btn btn_copykey" value="一键复制" :data-clipboard-text="scope.row.address" @click.native="copyInfo()" />
            <k-button v-show="scope.row.drawsStatus === 5" class="table-btn" value="发货" @click.native="sendPrize(scope.row.id)" />
            <k-button v-show="scope.row.drawsStatus === 6 || scope.row.drawsStatus === 11" class="table-btn" value="修改单号" @click.native="modifyDeliverNum(scope.row)" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="loadData"
    />
    <k-dialog
      :show-hide.sync="sendPrizeDialogShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="发货"
      :show-foot="false"
      :two-btn="true"
      @click="sendPrizeSave"
    >
      <div class="redraw-contanier">
        <el-form label-width="auto">
          <el-form-item label="快递单号：">
            <el-input v-model="sendPrizeDeliverNum" placeholder="请输入快递单号" />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
    <k-dialog
      :show-hide.sync="modifyDialogShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="修改单号"
      :show-foot="false"
      :two-btn="true"
      @click="modifyNumSave"
    >
      <div class="redraw-contanier">
        <el-form label-width="auto">
          <el-form-item label="原快递单号：">
            <el-input v-model="sendPrizeDeliverNum" disabled />
          </el-form-item>
          <el-form-item label="新快递单号：">
            <el-input v-model="newSendPrizeDeliverNum" placeholder="请输入快递单号" />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { listPrizeDrawData, getPrizeDrawStatus, cancelPrizeDraw, extendedTake, doDraw, setBuyPrice, updateCourierNumber } from '@/api/task/index'
import EditableCell from '@/components/EditableCell'
import ClipboardJS from 'clipboard'

export default {
  components: { Pagination, EditableCell },
  dicts: ['IDENTITY_TYPE'],
  data() {
    return {
      currentPrizeId: -1,
      sendPrizeDeliverNum: '',
      newSendPrizeDeliverNum: '',
      drawType: 1,
      goodsId: -1,
      sendPrizeDialogShow: false,
      modifyDialogShow: false,
      listData: [],
      multipleSelection: [],
      prizeDrawStatusList: [],
      timeValue: '',
      timeValueGet: '',
      getLimitDialog: {
        showHide: false
      },
      saveLimitInfo: {
        countLimit: undefined,
        priceLimit: undefined,
        drawCount: undefined,
        drawPercent: undefined,
        warningPercent: undefined
      },
      totalRows: 0, // 分页组件--数据总条数
      buyPricetotalData: 0,
      nowPricetotalData: 0,
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: '',
          start: ''
        },
        sort: '', // 排序字段 为对应列名,
        direction: '', // 排序 正向(asc)逆向(desc),
        userType: undefined, // 身份所属",
        drawStatus: undefined, // 提取状态",
        startTime: '', // 发起时间检索",
        endTime: '', // 发起时间检索",
        recipeStartTime: '', // 接受时间检索",
        recipeEndTime: '', // 接受时间检索",
        key: '' // 饰品名称'
      }
    }
  },
  watch: {
    timeValue(val) {
      this.listQuery.startTime = this.timeValue ? this.timeValue[0] : null
      this.listQuery.endTime = this.timeValue ? this.timeValue[1] : null
    },
    timeValueGet(val) {
      this.listQuery.recipeStartTime = this.timeValueGet ? this.timeValueGet[0] : null
      this.listQuery.recipeEndTime = this.timeValueGet ? this.timeValueGet[1] : null
    }
  },
  created() {
    this.loadData()
    this.getPrizeDrawStatus()
  },
  methods: {
    getDiffTime(milltime) {
      if (milltime === null) return ''
      const difftime = milltime / 1000 // 计算时间差,并把毫秒转换成秒
      const days = parseInt(difftime / 86400) // 天  24*60*60*1000
      const hours = parseInt(difftime / 3600) - 24 * days // 小时 60*60 总小时数-过去的小时数=现在的小时数
      // const minutes = parseInt(difftime % 3600 / 60) // 分钟 -(day*24) 以60秒为一整份 取余 剩下秒数 秒数/60 就是分钟数
      // const seconds = parseInt(difftime % 60) // 以60秒为一整份 取余 剩下秒数
      return days + '天' + hours + '小时'
    },
    sendPrize(id) {
      this.sendPrizeDeliverNum = ''
      this.currentPrizeId = id
      this.sendPrizeDialogShow = true
    },
    sendPrizeSave() {
      if (this.sendPrizeDeliverNum.length === 0) {
        this.$message.error('请输入快递单号')
        return
      }
      doDraw({ id: this.currentPrizeId, courierNumber: this.sendPrizeDeliverNum }).then(res => {
        this.sendPrizeDialogShow = false
        if (res.data.success) {
          this.loadData()
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.data.msg)
        }
        this.sendPrizeDeliverNum = ''
      })
    },
    modifyDeliverNum(row) {
      this.currentPrizeId = row.id
      this.sendPrizeDeliverNum = row.courierNumber
      this.modifyDialogShow = true
    },
    modifyNumSave() {
      if (this.newSendPrizeDeliverNum.length === 0) {
        this.$message.error('请输入快递单号')
        return
      }
      updateCourierNumber({ id: this.currentPrizeId, courierNumber: this.newSendPrizeDeliverNum }).then(res => {
        this.modifyDialogShow = false
        if (res.data.success) {
          this.loadData()
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.data.msg)
        }
        this.newSendPrizeDeliverNum = ''
        this.sendPrizeDeliverNum = ''
      })
    },
    copyInfo() {
      const clipboard = new ClipboardJS('.btn_copykey')
      clipboard.on('success', e => {
        this.$message.success('复制成功')
        //  释放内存
        e.clearSelection()
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // 不支持复制
        this.$message.error('复制出错')
        clipboard.destroy()
      })
    },
    updateBuyPrice(row) {
      setBuyPrice({ id: row.id, buyPrice: row.buyPrice }).then(res => {
        if (!res.data.success) {
          this.$message.error(res.data.msg)
        } else {
          this.loadData()
        }
      })
    },
    getPrizeDrawStatus() {
      getPrizeDrawStatus().then(res => {
        this.prizeDrawStatusList = res.data
      })
    },
    loadData() {
      listPrizeDrawData(this.listQuery).then(res => {
        const data = res.data
        this.listData = data.rows.map(row => {
          return {
            ...row,
            editMode: false
          }
        })
        this.totalRows = data.totalRows
        this.nowPricetotalData = data.totalData.nowPrice
        this.buyPricetotalData = data.totalData.buyPrice
      })
    },
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) { // 第一列
          sums[index] = '总计'
        } else if (column.property === 'nowPrice') {
          sums[index] = this.nowPricetotalData
        } else if (column.property === 'buyPrice') {
          sums[index] = this.buyPricetotalData
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 表格的排序条件发生变化的时候会触发该事件
    sortChange(column, prop, order) {
      this.listQuery.sort = column.prop
      if (column.order === 'ascending') {
        this.listQuery.direction = 'asc'
      } else if (column.order === 'descending') {
        this.listQuery.direction = 'desc'
      }
      this.handleFilter()
    },
    // 搜索查询事件
    handleFilter() {
      this.listQuery.pager.pageNo = 1
      this.loadData()
    },

    customReDrawSave() {

    },
    // 取消发货
    cancelPrizeDraw() {
      const _vue = this
      if (_vue.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据进行操作！')
        return
      }
      const selections = _vue.multipleSelection
      this.$confirm('确定要取消发货吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids = []
        for (var i = 0; i < selections.length; i++) {
          ids.push(selections[i].id)
        }
        cancelPrizeDraw({ 'ids': ids }).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.loadData()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
      })
    },

    // 延长收货
    extendedTakeClick() {
      const _vue = this
      if (_vue.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据进行取消！')
        return
      }
      const selections = _vue.multipleSelection
      this.$confirm('确定要延长收货吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids = []
        for (var i = 0; i < selections.length; i++) {
          ids.push(selections[i].id)
        }
        extendedTake({ 'ids': ids }).then(res => {
          if (res.data.success) {
            this.$message.success('延长收货成功')
            this.loadData()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style lang="scss" scoped>
$menuText:#14162E; // 侧边栏字体颜色
$hoverColor:#1D143C;// 鼠标停留主色调浅色
$mainColor:#3b425d;// 主色调
.filter-container {
 width: 100%;
  height: 48px;
  line-height: 48px;
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }
  .width-control{
    width: 120px;
  }
  .kInput{
    position:absolute;
    right: 20px;
  }
  .filter-title{
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162E;
  }
  .right-item{
    margin-right: 10px;
  }
}

.extract_data {
  height: 35px;
  width: 100%;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
    padding-right: 20px;
    box-sizing: border-box;
  .extract_data_left {
    display: flex;
    align-items: center;
    p {
      width: 100px;
      height: 35px;
      font-size: 14px;
      line-height: 35px;
      text-align: center;
      border-radius: 4px;
      cursor: pointer;
      background: #3b425d;
      color: #fff;
      margin-right: 10px;

    }
  }

  span {
    width: 100px;
    height: 35px;
    font-size: 14px;
    line-height: 35px;
    text-align: center;
    border-radius: 4px;
    background: #F8F7FB;
    cursor: pointer;
  }
}

.el-message-box {
  .el-button {
    border: 1px solid #3b425d;
    color: #3b425d;
    background-color: rgba($color: #3b425d, $alpha: .1);
  }
}
.redraw-contanier{
  padding: 20px;
}

</style>
